//
//  HJStatusListViewModel.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/20.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import SDWebImage

class HJStatusListViewModel: NSObject {
    
    var statusArray: [HJStatusViewModel]?
    func loadData(isPullup:Bool,finish:((isSuccess:Bool) -> ())){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var max_id:Int64 = 0
        var since_id:Int64 = 0
        if isPullup{//上拉加载更多
            max_id = statusArray?.last?.status?.id ?? 0
            //去除重复
            if max_id != 0 {
                max_id--
            }
        }else{//下拉刷新
            since_id = statusArray?.first?.status?.id ?? 0
        }
        
        
        let params = [
            "access_token": HJUserAccountViewModel.shareAccount.accessToken ?? "",
            "max_id": "\(max_id)",
            "since_id":"\(since_id)"
        ]
        
        HJNetworkTools.shareTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
            if error != nil {
                finish(isSuccess: false)
                return
            }
            guard let dict = responseObject as? [String: AnyObject] else{
                print("请求数据不是字典")
                finish(isSuccess: false)
                return
            }
//            print(dict)
            guard let dicts = dict["statuses"] as? [[String: AnyObject]] else{
                finish(isSuccess: false)

                return
            }
            var arrM = [HJStatusViewModel]()
            for value in dicts {
                let status = HJStatus(dict: value)
                let viewModel = HJStatusViewModel()
                viewModel.status = status
                arrM.append(viewModel)
            }
//            self.statusArray = arrM
            
            if self.statusArray == nil{
                self.statusArray = [HJStatusViewModel]()
            }
            if isPullup{
                self.statusArray = self.statusArray! + arrM
            }else{
                self.statusArray = arrM + self.statusArray!
            }
            print("更新\(arrM.count)条微博")
            self.cacheSingleImage(arrM, finish: finish)
//            finish(isSuccess: true)
        }
    }
    
    
    private func cacheSingleImage(array:[HJStatusViewModel], finish:(isSuccess:Bool) -> ()){
        
        let group:dispatch_group_t = dispatch_group_create()
        
        for value in array {
            let originalPicUrls = value.status?.pic_urls
            let retweetPicUrls = value.status?.retweeted_status?.pic_urls
            let picUrls = (originalPicUrls == nil || originalPicUrls?.count == 0) ? retweetPicUrls : originalPicUrls
            if picUrls?.count == 1 {
                //单图下载地址
                let urlString = picUrls?.first?.thumbnail_pic
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //监听下载完成

                    value.updateSingleImagePictureViewSize()

                    dispatch_group_leave(group)
                })
                
            }
        }
        //全部下载完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finish(isSuccess: true)
        }
    }
}
